package social.hub.impl.jersey.api;

import static social.hub.api.google.buzz.BuzzConstants.*;

import java.util.List;

import javax.ws.rs.core.MediaType;

import social.hub.api.ApiConfig;
import social.hub.api.google.buzz.BuzzActivity;
import social.hub.api.google.buzz.BuzzApi;
import social.hub.api.google.buzz.BuzzProfile;
import social.hub.api.google.buzz.util.BuzzAtivityRequest;
import social.hub.api.google.buzz.util.BuzzDataRequest;
import social.hub.api.google.buzz.util.BuzzPersonFeedResponse;
import social.hub.api.google.buzz.util.BuzzPersonResponse;
import social.hub.impl.jersey.util.ClientFactory;
import social.hub.util.UrlBuilder;

import com.sun.jersey.api.client.Client;

public class JerseyBuzzApi implements BuzzApi {

	private final Client client;

	public JerseyBuzzApi(ApiConfig config) {
		client = ClientFactory.createClient(config, OAUTH_SCOPE);
	}

	@Override
	public void createAtivity(String status) {
		createAtivity(status, SELF_ID);
	}

	@Override
	public void createAtivity(String status, String buzzId) {

		String url = buildUrl(NEW_ACTIVITY_URL, buzzId);

		BuzzActivity ativity = new BuzzActivity();
		ativity.setContent(status);

		BuzzAtivityRequest requestAtivity = new BuzzAtivityRequest();
		requestAtivity.setObject(ativity);

		BuzzDataRequest<BuzzAtivityRequest> request = new BuzzDataRequest<BuzzAtivityRequest>(requestAtivity);

		client.resource(url).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(request);

	}

	@Override
	public List<BuzzProfile> getFolloweds() {
		return getFolloweds(SELF_ID);
	}

	@Override
	public List<BuzzProfile> getFolloweds(String buzzId) {

		String url = buildUrl(FOLLOWEDS_URL, buzzId);

		BuzzPersonFeedResponse feedResponse = client.resource(url).get(BuzzPersonFeedResponse.class);

		return feedResponse.getData().getEntry();

	}

	@Override
	public List<BuzzProfile> getFollowers() {
		return getFollowers(SELF_ID);
	}

	@Override
	public List<BuzzProfile> getFollowers(String buzzId) {

		String url = buildUrl(FOLLOWERS_URL, buzzId);

		BuzzPersonFeedResponse feedResponse = client.resource(url).get(BuzzPersonFeedResponse.class);

		return feedResponse.getData().getEntry();

	}

	@Override
	public BuzzProfile getProfile() {
		return getProfile(SELF_ID);
	}

	@Override
	public BuzzProfile getProfile(String buzzId) {

		String url = buildUrl(PROFILE_URL, buzzId);

		BuzzPersonResponse response = client.resource(url).get(BuzzPersonResponse.class);

		return response.getData();

	}

	private String buildUrl(String baseUrl, String buzzId) {
		return new UrlBuilder(baseUrl, false).addUrlParan("profileId", buzzId).addQueryParan("alt", "json").toString();
	}

}
